import React, {useEffect, useRef, useState} from "react";
import findup from "findup-element/index";
import ResizableBoxComp from "../ResizableBoxComp";
import {isNumber} from "lodash-es";
import {sleepFunc} from "jh-utils";
import FieldCtrl from "../Config/FieldCtrl";

// type ResizableTitleProps = Pick<ResizableProps, 'onResize' | 'onResizeStop' | 'onResizeStart' | 'width'> & {
//     colInd: number,
//     isBig: boolean,
//     [x: string]: any
// }

// const ResizeableTitle: React.FC<ResizableTitleProps> = props => {
const ResizeableTitle = props => {
    const {onResize, onResizeStop, onResizeStart, width, colInd, isBig, handle, rowSelect, fieldCtrl, ...restProps} = props;

    if (!width) {
        return <th {...restProps} >
            {fieldCtrl === FieldCtrl.REQUIRED && <span className={'text-danger'}>*</span>}
            {restProps.children}
        </th>;
    }

    const thRef = useRef(null);
    const [initW, setInitW] = useState(isNumber(width) ? width : 0);

    useEffect(() => {

        if (thRef.current && initW <= 0) {

            sleepFunc(isBig ? 2000 : 1000).then(() => {

                if (thRef) {
                    let thDom = findup(thRef.current, (parent) => ('TH' === parent.tagName));

                    if (thDom) {
                        setInitW(thDom.offsetWidth);
                    }
                }
            });
        }
    }, []);

    const onResizeStartFunc = (e, data) => {
        // 找到 <div class="ant-table-container"> 下的 <table class="ant-table-header">
        let headTableDom = findup(e.target, (parent) => ('TABLE' === parent.tagName));

        if (headTableDom) {
            let colgroup = headTableDom.getElementsByTagName('colgroup');
            let colIndex = rowSelect ? colInd + 1 : colInd;

            if (colgroup && colgroup[0] && colgroup[0].childNodes && colgroup[0].childNodes[colIndex]) {
                // 要将 table > colgroup > col 的 width 设置为 auto，才能拖动表头
                let colLen = colgroup[0].childNodes.length;
                let colDom = colgroup[0].childNodes[colIndex];
                colDom.style.width = 'auto';
            }
        }
        onResizeStart && onResizeStart(e, data);
    };

    const onResizeFunc = (e, data) => {

        // if (data.size.width >= 50) {
        // 不是单页展示大量数据时，才在调整大小的同时，触发传入的 props.onResize 回调，避免卡顿
        if (false === isBig) {
            onResize && onResize(e, data);
        }
        // else {
        // 如果是单页展示大量数据，则在调整大小的动作结束之后（onResizeStop），再触发传入的 props.onResize
        // 这里不做任何处理
        // }
        // }
    };

    const onResizeStopFunc = (e, data) => {
        // if (data.size.width >= 50) {

        if (true === isBig) {
            onResize && onResize(e, data);
            onResizeStop && onResizeStop(e, data);
        } else {
            onResizeStop && onResizeStop(e, data);
        }
        // }
    };

    return (
        <ResizableBoxComp
            colInd={colInd}
            width={initW}
            height={0}
            axis="x"
            handle={(resizeHandle) => <span
                className={`react-resizable-handle react-resizable-handle-${resizeHandle}`}
                onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                }}
            />
            }
            resizeHandles={['right' === restProps.fixed ? 'w' : 'e']}
            onResizeStart={onResizeStartFunc}
            onResize={onResizeFunc}
            onResizeStop={onResizeStopFunc}
            draggableOpts={{enableUserSelectHack: false, grid: [5, 5]}}
        >
            {({width}) => (
                <th
                    ref={thRef}
                    {...restProps}
                    style={restProps.style ? {...restProps.style, width} : {width}}
                >
                    {fieldCtrl === FieldCtrl.REQUIRED && <span className={'text-danger'}>*</span>}
                    {restProps.children}
                </th>
            )}
        </ResizableBoxComp>
    );
};

export default ResizeableTitle;